// package1/pages/views/jobTab/chat/chat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 全局变量，控制全局显示样式
    globalData:{
      StatusBar:'',
      Custom:'',
      CustomBar:'',
      sysInfo: {}
    },
    // 消息列表（存在缓存中）
    newsList:[
      {
        content: "您好",
        createTime: 1719196048000,
        id: "107",
        isRead: true,
        receiverId: "949968616440549376",
        roomId: "85",
        senderId: "964121322312949760"
      },
      {
        content: "来了来了",
        createTime: 1719196053000,
        id: "108",
        isRead: true,
        receiverId: "949968616440549376",
        roomId: "85",
        senderId: "964121322312949760"
      },
      {
        content: "欢迎参加零工求职！",
        createTime: 1719196092000,
        id: "110",
        isRead: true,
        receiverId: "964121322312949760",
        roomId: "85",
        senderId: "949968616440549376"
      },
      {
        content: "好的好的",
        createTime: 1719196080000,
        id: "109",
        isRead: true,
        receiverId: "964121322312949760",
        roomId: "85",
        senderId: "949968616440549376"
      }
    ],
    // 用户唯一标识
    senderId: '949968616440549376',
    // 新消息
    news:'',
    // 聊天列表高度
    curra:0,
    // 软键盘是否关闭
    alcur:false,
    // 视野（软键盘高度）
    vision:'',
    // 定时器对象
    time:'',
    // 期间
    duration:'',
    // 
    cuindex:'',
    // ai回答
    aiAnswer:'',
    sockTack: null,
    limit: 0,
    roomId: '85',
    ueId: '',
    urId: '',
    otherName: null,
    otherPortrait: '',
    userName: '李小龙',
    userPortrait: '',
    otherSex: '0',
    userSex: '1',
    lockReconnect: true,
    handleClose: false,
    focus: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(options)
    let that = this;
    // 获取系统信息
    wx.getSystemInfo({
      success: e => {
        console.log(e)
        that.data.globalData.sysInfo = e
        that.data.globalData.StatusBar = e.statusBarHeight;
        let capsule = wx.getMenuButtonBoundingClientRect();
        console.log(capsule)
        if (capsule) {
          that.data.globalData.Custom = capsule;
          that.data.globalData.CustomBar = capsule.bottom + capsule.top - (e.statusBarHeight + 15);
        } else {
          that.data.globalData.CustomBar = e.statusBarHeight + 50;
        }
      }
    });
    that.setData({
      ueId: options.ueId,
      urId: options.urId,
      // senderId: wx.getStorageSync('userId'),
      // senderId: wx.getStorageSync('userId'),
      // 全局变量
      globalData: that.data.globalData,
    });
    console.log(this.data.ueId, 'diyi')
    // this.cuinbut();
    let roomData = {
      ueId: options.ueId,
      urId: options.urId,
      userType: options.userType
    }
    console.log(roomData)
    // this.getRoom(roomData)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.cuinbut();
  },

  getRoom (data) {
    wxReq.openRoom(data).then(res => {
      console.log(res)
      if(res.code === 0) {
        let data = res.data
        console.log(data,1111)
        this.setData({
          newsList: res.data.messageList.reverse(),
          roomId: data.roomId,
          otherName: data.otherName,
          otherPortrait: data.otherPortrait,
          userName: data.userName,
          userPortrait: data.userPortrait,
          userSex: data.userSex,
          otherSex: data.otherSex
        })
        this.cuinbut();
        this.linkSocket()
      }
    }).catch((err) => {
      console.log('进行链接的报错', err)
    })
  },

  linkSocket(){
    let that = this
    this.sockTack = wx.connectSocket({
      url: 'wss://ggjytest.qxnrcsc.com/jyfw/qzzpapi/chater/laborerWebsocket/socket/chatting/'+ this.data.roomId+'/'+ this.data.senderId,// 正式
      // url: 'wss://ggjy.klmy.gov.cn/klmyjyfw/qzzpapi/chater/laborerWebsocket/socket/chatting/'+ this.data.roomId+'/'+ this.data.senderId,// 正式
      header: {
        'Authorization': wx.getStorageSync('ticket'),
      },
      success() {
        console.log('连接成功')
        that.initEventHandle()
      }
    })
  },
  initEventHandle(){
    let that = this
    wx.onSocketMessage((res) => {
      console.log(res)
      let data = JSON.parse(res.data)
      const newChatList = [...that.data.newsList, {
        content: data.content,
        senderId: data.senderId,
      }];
      that.setData({
        newsList: newChatList,
      })
      that.cuinbut();
      //收到消息
      // if (res.data == "pong"){
      //   heartCheck.reset().start()
      // }else{

      // }
    })
    wx.onSocketOpen(()=>{
      console.log('WebSocket连接打开')
      let data = {roomId:null, receiverId:null, senderId:null, content:'维持连接',}
      that.data.timeoutObj = setInterval(() => {
        wx.sendSocketMessage({
          data: JSON.stringify(data),
          success(){
            console.log("维持连接");
          }
        });
      }, 10000);
    })
    wx.onSocketError((res)=>{ 
      console.log('WebSocket连接打开失败')
      this.reconnect()
    })
    wx.onSocketClose((res)=> {
      console.log('WebSocket 已关闭！')
      console.log(this.data.handleClose)
      clearTimeout(this.data.timeoutObj);

      if(!this.data.handleClose) {
        this.setData({lockReconnect: false})
        this.reconnect()
      }
    })
  },
  reconnect(){
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    clearTimeout(this.timer)
    if (this.data.limit<12){
      this.timer = setTimeout(() => {
        console.log('重连2')
        this.linkSocket();
        this.lockReconnect = false;
      }, 2000);
      this.setData({
        limit: this.data.limit+1
      })
    }
  },
  /**
   * 失去焦点事件
   */
  getkey:function(e){
    console.log(e.detail.height)
    // 这个setdata的值没有用，wxml中无应用
    this.setData({
      focus: true,
      curra: e.detail.height,
    })
    this.cuinbut();
  },
/**
 * 获取焦点事件
 */
  getblur:function(e){
    this.setData({
      focus: false,
      curra: 0,
    })
    this.cuinbut();
  },
  /**
   * 获取input输入的消息
   */
  moninput:function(e){
    this.setData({
      news: e.detail.value,
    })
  },
  /**
   * 滚动条开始滚动
   */
  scrollstart:function(e){
  },
  /**
   * 发送消息接口
   */
  message(){
    let that = this
    if(that.data.news) {
      let data = {
        content: this.data.news,
        receiverId: this.data.senderId === this.data.ueId?this.data.urId:this.data.ueId,
        roomId: this.data.roomId,
        senderId: this.data.senderId,
        userType: wx.getStorageSync('userType')
      }
      console.log(JSON.stringify(data))
      wx.sendSocketMessage({
        data: JSON.stringify(data),
        success(res){
          console.log("发送ping成功", res);
          const newChatList = [...that.data.newsList, {
            content: that.data.news,
            senderId: that.data.senderId,
          }];
          that.setData({
            focus: false,
            news: '',
            newsList: newChatList,
          })
          that.cuinbut();
        },
        fail() {
          wx.showToast({
            title: '发送失败',
            icon: 'none'
          })
        }
      });
    }
  },
  /**
   * 聊天接口
   * @param str 用户发的消息
   */
  aiChat:function(str)
  {
    var self = this;
    // 请求后台接口获取文章列表
    // wx.request({
      // 请求连接
      // url: 'https://guanchao.site/index/im/tencentAI',
      // // 请求所需要的的参数
      // data: {
      //   'str':str
      // },
      // success(result){
        // self.data.aiAnswer = result.data.data.answer;
        // if(result.data.msg != 'ok')
        // {
          self.data.aiAnswer = "先别测，代码还没写完";
        // }
        const newChatList = [...self.data.newsList, {
          news_type: 'text',
          news_centent: self.data.aiAnswer,
          openid: 'ai',
          logo:'https://guanchao.site/uploads/atricle/5c0a66cac42cb.jpeg'
        }];
        self.setData({
          animation: true,
          newsList: newChatList,
          news: '',
        })
        console.log('newChatList', newChatList)
        wx.setStorageSync('newsList', newChatList);
        self.cuinbut();
      // }
    // });
  },

  /**
   * 监听页面底部输入框
   */
  cuinbut:function(e){
    let that = this
    setTimeout(function () {
      wx.createSelectorQuery().select('#chat-height').boundingClientRect(function (rect) {
        that.setData({
          // 底部输入框的高度
          chatheight: parseFloat(rect.height) + parseFloat(that.data.curra)+8,
          // 当前最后一条信息
          curr: 'jump' + JSON.stringify(that.data.newsList.length - 1)
        })
      }).exec()
    }, 100);
    // console.log(wx.getStorageSync('newsList'));
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    let data = {receiverId:this.data.senderId === this.data.ueId?this.data.urId:this.data.ueId}
    wx.sendSocketMessage({
      data: JSON.stringify(data),
      success(){
        console.log("同步");
      }
    })
    this.setData({handleClose: true})
    wx.closeSocket()
    clearTimeout(this.data.timeoutObj);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})